<template>
  <el-form :model="form" label-position="top">
    <el-form-item label="产品名称" required>
      <el-autocomplete
        v-model="form.productName"
        :fetch-suggestions="queryProducts"
        placeholder="请输入产品名称"
        clearable
        class="form-input"
        value-key="name"
        @select="handleProductSelect"
        @focus="handleProductFocus"
        :trigger-on-focus="true"
        :highlight-first-item="true"
        @change="handleProductNameChange"
      >
        <template #default="{ item }">
          <div class="product-item">
            <div>{{ item.name }}</div>
            <div class="product-description" v-if="item.description">{{ item.description }}</div>
          </div>
        </template>
      </el-autocomplete>
    </el-form-item>

    <el-form-item label="查询深度">
      <el-slider
        v-model="form.depth"
        :min="1"
        :max="5"
        :step="1"
        :marks="{1:'1', 2:'2', 3:'3', 4:'4', 5:'5'}"
        show-stops
        class="form-slider"
      />
    </el-form-item>

    <el-form-item label="关系方向" class="direction-selector">
      <el-radio-group v-model="form.direction" size="large" class="direction-radio-group">
        <el-radio label="both">上下游</el-radio>
        <el-radio label="upstream">上游</el-radio>
        <el-radio label="downstream">下游</el-radio>
      </el-radio-group>
    </el-form-item>

    <!-- 功能按钮区域，调整为水平布局，将关键材料识别按钮调整至与查询按钮同级 -->
    <el-divider content-position="center">功能操作</el-divider>
    
    <div class="function-buttons">
      <!-- 产品链查询按钮 -->
      <el-button type="primary" @click="handleQuery" class="query-button">
        <el-icon><Search /></el-icon> 查询产品链
      </el-button>
      
      <!-- 关键材料识别按钮 -->
      <el-button type="success" @click="handleKeyMaterials" class="key-materials-button">
        <el-icon><Goods /></el-icon> 关键材料识别
      </el-button>
      
      <!-- 重置按钮 -->
      <el-button @click="handleReset" class="reset-button">
        <el-icon><Refresh /></el-icon> 重置
      </el-button>
    </div>
  </el-form>
</template>

<script>
import { ref, reactive, watch } from 'vue';
import { Search, Refresh, Goods } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { searchProducts } from '@/api/graphAnalysis';

export default {
  name: 'ProductChainForm',
  components: {
    Search,
    Refresh,
    Goods
  },
  props: {
    loading: {
      type: Boolean,
      default: false
    }
  },
  emits: ['query', 'key-materials', 'reset'],
  setup(props, { emit }) {
    const form = reactive({
      productName: '',
      selectedProduct: null,
      depth: 2,
      direction: 'both'
    });

    // 加载默认产品列表方法保留，但只在用户点击搜索框时调用
    const loadDefaultProducts = () => {
      queryProducts('', (suggestions) => {
        // 自动完成组件会处理结果
      });
    };

    // 监听产品名称变化
    watch(() => form.productName, (newVal, oldVal) => {
      // 如果用户清空输入框，不自动加载产品列表
      // if (newVal === '' && oldVal !== '') {
      //   loadDefaultProducts();
      // }
    });

    const queryProducts = async (queryString, callback) => {
      try {
        // 只有当用户主动点击搜索框或输入时才调用API
        const response = await searchProducts({
          keyword: queryString || ''
        });
        
        const products = Array.isArray(response) ? response : [];
        const suggestions = products.map(item => ({
          value: item.name || '',
          label: item.name || '',
          ...item
        }));
        
        callback(suggestions);
      } catch (error) {
        console.error('搜索产品失败:', error);
        ElMessage.error('搜索产品失败，请稍后重试');
        callback([]);
      }
    };

    const handleProductSelect = (item) => {
      form.selectedProduct = item;
      // 移除选择产品后自动查询的行为
      // handleAutoQuery();
    };

    // 处理产品名称变化
    const handleProductNameChange = () => {
      // 这里可以添加其他逻辑如果需要
    };

    // 获取焦点时触发产品搜索，这是唯一调用接口的地方
    const handleProductFocus = () => {
      if (!form.productName) {
        loadDefaultProducts();
      }
    };

    // 查询产品链
    const handleQuery = () => {
      emit('query', {
        productName: form.productName,
        depth: form.depth,
        direction: form.direction
      });
    };

    // 关键材料识别
    const handleKeyMaterials = () => {
      console.log('[ProductChainForm] 点击关键材料识别按钮');
      
      // 简化处理，移除直接操作路由的代码
      // 直接触发事件，让父组件处理状态更新
      emit('key-materials');
    };

    // 重置表单
    const handleReset = () => {
      form.productName = '';
      form.selectedProduct = null;
      form.depth = 2;
      form.direction = 'both';
      emit('reset');
    };

    return {
      form,
      queryProducts,
      handleQuery,
      handleKeyMaterials,
      handleReset,
      handleProductSelect,
      handleProductNameChange,
      handleProductFocus
    };
  }
};
</script>

<style scoped>
.form-input {
  width: 100%;
}

.form-slider {
  margin-top: 8px;
  height: 34px;
}

.direction-selector {
  margin-top: 12px;
}

.direction-radio-group {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.direction-radio-group :deep(.el-radio) {
  margin-right: 0;
  padding: 8px 16px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

/* 功能按钮区域样式 */
.function-buttons {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 10px;
  margin-top: 15px;
}

.query-button,
.key-materials-button,
.reset-button {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  flex: 1;
  min-width: 120px;
  max-width: 200px;
}

.product-item {
  padding: 8px 0;
}

.product-description {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>